package com.senlingspace.system.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.enums.LakalaTradeStateEnum;
import com.senlingspace.common.enums.OrderBusinessStatus;
import com.senlingspace.common.enums.RelatedType;
import com.senlingspace.common.utils.*;
import com.senlingspace.system.domain.Project;
import com.senlingspace.system.domain.SlkjOrder;
import com.senlingspace.system.domain.SlkjOrderSplitSnapshot;
import com.senlingspace.system.domain.vo.SlkjCopyrightVo;
import com.senlingspace.system.mapper.ProjectMapper;
import com.senlingspace.system.mapper.SlkjOrderMapper;
import com.senlingspace.system.mapper.SlkjOrderSplitSnapshotMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.senlingspace.system.mapper.SlkjCopyrightMapper;
import com.senlingspace.system.domain.SlkjCopyright;
import com.senlingspace.system.service.ISlkjCopyrightService;
import org.springframework.util.CollectionUtils;

/**
 * 版权方列表Service业务层处理
 *
 * @author SenlingSpace
 * @date 2024-07-02
 */
@Service
public class SlkjCopyrightServiceImpl implements ISlkjCopyrightService {
    @Autowired
    private SlkjCopyrightMapper slkjCopyrightMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private SlkjOrderMapper slkjOrderMapper;
    @Autowired
    private SlkjOrderSplitSnapshotMapper slkjOrderSplitSnapshotMapper;

    /**
     * 查询版权方列表
     *
     * @param copyrightId 版权方列表主键
     * @return 版权方列表
     */
    @Override
    public SlkjCopyright selectSlkjCopyrightByCopyrightId(Long copyrightId) {
        return slkjCopyrightMapper.selectSlkjCopyrightByCopyrightId(copyrightId);
    }

    /**
     * 查询版权方列表列表
     *
     * @param slkjCopyright 版权方列表
     * @return 版权方列表
     */
    @Override
    public List<SlkjCopyright> selectSlkjCopyrightList(SlkjCopyright slkjCopyright) {
        PageUtils.startPage();
        return slkjCopyrightMapper.selectSlkjCopyrightList(slkjCopyright);
    }

    /**
     * 新增版权方列表
     *
     * @param slkjCopyright 版权方列表
     * @return 结果
     */
    @Override
    public int insertSlkjCopyright(SlkjCopyright slkjCopyright) {
        slkjCopyright.setCopyrightNumber(NumberGenerator.getCharacters(13));
        slkjCopyright.setStatus(0);// 0=正常，1=删除
        slkjCopyright.setCreateTime(DateUtils.getNowDate());
        slkjCopyright.setUserId(SecurityUtils.getUserId());
        slkjCopyright.setDeptId(SecurityUtils.getDeptId());
        return slkjCopyrightMapper.insertSlkjCopyright(slkjCopyright);
    }

    /**
     * 修改版权方列表
     *
     * @param slkjCopyright 版权方列表
     * @return 结果
     */
    @Override
    public int updateSlkjCopyright(SlkjCopyright slkjCopyright) {
        slkjCopyright.setUpdateTime(DateUtils.getNowDate());
        return slkjCopyrightMapper.updateSlkjCopyright(slkjCopyright);
    }

    /**
     * 批量删除版权方列表
     *
     * @param copyrightIds 需要删除的版权方列表主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteSlkjCopyrightByCopyrightIds(Long[] copyrightIds) {

        for (Long copyrightId : copyrightIds) {
            Project project = new Project();
            project.setCopyrightId(copyrightId);
            List<Project> projects = projectMapper.selectProjectList(project);
            if (!CollectionUtils.isEmpty(projects)) {
                SlkjCopyright copyright = slkjCopyrightMapper.selectSlkjCopyrightByCopyrightId(copyrightId);
                return AjaxResult.warn("版权方下存在项目，禁止删除！");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除版权方列表信息
     *
     * @param copyrightId 版权方列表主键
     * @return 结果
     */
    @Override
    public int deleteSlkjCopyrightByCopyrightId(Long copyrightId) {
        return slkjCopyrightMapper.deleteSlkjCopyrightByCopyrightId(copyrightId);
    }

    @Override
    public List<SlkjCopyright> copyrightSelected(SlkjCopyright copyright) {
        return slkjCopyrightMapper.selectSlkjCopyrightList(copyright);
    }

    @Override
    public PageInfo<SlkjCopyrightVo> copyrightDetail(Date startTime, Date endTime, Long shopId, String projectName, String copyrightName) {
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderLists(startTime, endTime, shopId, projectName);
        if (CollectionUtils.isEmpty(slkjOrders)) {
            return new PageInfo<>(Lists.newArrayList());
        }

        List<SlkjCopyrightVo> slkjCopyrightVos = new ArrayList<>();
        for (SlkjOrder order : slkjOrders) {
            if (order.getPaymentStatus().equals(LakalaTradeStateEnum.SUCCESS.name())) {
                // 获取项目信息
                Project project = projectMapper.selectProjectByProjectId(order.getProjectId());
                String projectNames = project.getName();

                // 获取版权方信息
                SlkjCopyright copyright = slkjCopyrightMapper.selectSlkjCopyrightByCopyrightId(project.getCopyrightId());

                // 将创建时间转换为只包含日期的部分
                LocalDate orderDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                // 查找是否有已存在的记录
                boolean found = false;
                for (SlkjCopyrightVo existingVo : slkjCopyrightVos) {
                    LocalDate existingDate = existingVo.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                    if (existingDate.equals(orderDate) && existingVo.getProjectName().equals(order.getProjectName())) {
                        // 如果日期和项目名称相同，累加金额
                        List<SlkjOrderSplitSnapshot> snapshots = slkjOrderSplitSnapshotMapper.selectByOrderId(order.getOrderId());

                        // 注意：这里存储的金额单位是 毫，转为元的时候，需要除以10000，且必须保留后四位小数，不做四舍五入操作
                        long sumprofitShareAmountTotal = snapshots.stream()
                                .filter(snapshot -> snapshot.getRelatedType().equals(RelatedType.PROJECT.getCode()) && snapshot.getProfitShareAmount() != null)
                                .mapToLong(SlkjOrderSplitSnapshot::getProfitShareAmount)
                                .sum();
                        existingVo.setAmount(MoneyUtils.hao2Yuan(sumprofitShareAmountTotal));
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    // 如果没有找到相同的日期和项目名称，则创建新记录并添加到列表中
                    SlkjCopyrightVo slkjCopyrightVo = new SlkjCopyrightVo();
                    slkjCopyrightVo.setCopyrightName(copyright.getCompanyName());
                    slkjCopyrightVo.setCreateTime(order.getCreateTime());
                    slkjCopyrightVo.setShopName(order.getShopName());
                    slkjCopyrightVo.setProjectName(projectNames);

                    List<SlkjOrderSplitSnapshot> snapshots = slkjOrderSplitSnapshotMapper.selectByOrderId(order.getOrderId());
                    for (SlkjOrderSplitSnapshot snapshot : snapshots) {
                        if (snapshot.getRelatedType().equals(RelatedType.PROJECT.getCode()) && snapshot.getProfitShareAmount()!=null) {
                            slkjCopyrightVo.setAmount(MoneyUtils.hao2Yuan(snapshot.getProfitShareAmount()));
                        }
                    }
                    slkjCopyrightVos.add(slkjCopyrightVo);
                }
            }
        }
        return new PageInfo<>(slkjCopyrightVos);
    }

    @Override
    public PageInfo<SlkjCopyrightVo> copyrightSummary(Date startTime, Date endTime, Long shopId) {
        PageHelper.clearPage(); // 清除PageHelper的状态

        // 查询订单
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByList(startTime, endTime, shopId);
        if (CollectionUtils.isEmpty(slkjOrders)) {
            return new PageInfo<>(Collections.emptyList());
        }

        // 创建一个 map 用于存储结果，key 为门店名称+投资方
        Map<String, SlkjCopyrightVo> resultMap = new HashMap<>();

        for (SlkjOrder order : slkjOrders) {
            if (LakalaTradeStateEnum.SUCCESS.name().equals(order.getPaymentStatus())) {
                Project project = projectMapper.selectProjectByProjectId(order.getProjectId());
                SlkjCopyright copyright = slkjCopyrightMapper.selectSlkjCopyrightByCopyrightId(project.getCopyrightId());

                // 获取订单日期
                LocalDate orderDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                // 构造 key
                String key = order.getShopName() + "-" + copyright.getCompanyName();

                // 查询分账快照
                List<SlkjOrderSplitSnapshot> snapshots = slkjOrderSplitSnapshotMapper.selectByOrderId(order.getOrderId());

                // 累加或创建记录
                SlkjCopyrightVo vo = resultMap.get(key);
                if (vo == null) {
                    vo = new SlkjCopyrightVo();
                    vo.setCreateTime(order.getCreateTime()); // 保留原始时间戳，用于排序
                    vo.setShopName(order.getShopName());
                    vo.setCopyrightName(copyright.getCompanyName());
                    vo.setAmount("0");
                    vo.setRatio(BigDecimal.ZERO); // 初始化比例
                    resultMap.put(key, vo);
                } else {
                    // 更新时间为最新时间
                    if (order.getCreateTime().after(vo.getCreateTime())) {
                        vo.setCreateTime(order.getCreateTime());
                    }
                }

                for (SlkjOrderSplitSnapshot snapshot : snapshots) {
                    if (snapshot.getRelatedType().equals(RelatedType.PROJECT.getCode()) && snapshot.getProfitShareAmount() != null) {
                        // 设置调整后的金额到 slkjCopyrightVo 的 amount 属性中
                        vo.setAmount(MoneyUtils.hao2Yuan(snapshot.getProfitShareAmount()));
                        vo.setRatio(snapshot.getCurrentUseRatio()); // 更新比例
                    }
                }
            }
        }

        // 将 map 的值转换为 list，并按时间降序排序
        List<SlkjCopyrightVo> copyrightVos = new ArrayList<>(resultMap.values());
        copyrightVos.sort(Comparator.comparing(SlkjCopyrightVo::getCreateTime).reversed());

        PageInfo<SlkjCopyrightVo> pageInfo = new PageInfo<>(copyrightVos);
        return pageInfo;
    }



    @Override
    public List<SlkjCopyrightVo> copyrightTrend(Date startTime, Date endTime, String projectName, String mobile) {
        // 获取指定日期所在月份的第一天
        LocalDate localDate = endTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate firstDayOfMonth = localDate.withDayOfMonth(1);
        Date dateFirstDayOfMonth;
        if (startTime == null) {
            dateFirstDayOfMonth = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
        } else {
            dateFirstDayOfMonth = startTime;
        }
        List<SlkjCopyrightVo> slkjCopyrightVos = slkjOrderMapper.selectOrderByTimeList(dateFirstDayOfMonth, endTime, projectName);
        // 在返回之前进行正序排序
        slkjCopyrightVos.sort(Comparator.comparing(SlkjCopyrightVo::getCreateTime));
        BigDecimal amount = BigDecimal.valueOf(0L);
        // for (SlkjCopyrightVo slkjCopyrightVo : slkjCopyrightVos) {
        //     amount = amount.add(slkjCopyrightVo.getAmount());
        //     slkjCopyrightVo.setAmount(amount);
        // }
        return slkjCopyrightVos;
    }

    @Override
    public List<SlkjCopyrightVo> copyrightTrendDay(Date startTime, Date endTime, String projectName, String mobile) {
        // 获取指定日期所在月份的第一天
        LocalDate localDate = endTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate firstDayOfMonth = localDate.withDayOfMonth(1);
        Date dateFirstDayOfMonth;
        if (startTime == null) {
            dateFirstDayOfMonth = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
        } else {
            dateFirstDayOfMonth = startTime;
        }
        List<SlkjCopyrightVo> slkjCopyrightVos = slkjOrderMapper.selectOrderByTimeList(dateFirstDayOfMonth, endTime, projectName);
        // 在返回之前进行正序排序
        slkjCopyrightVos.sort(Comparator.comparing(SlkjCopyrightVo::getCreateTime));
        return slkjCopyrightVos;
    }

    @Override
    public List<SlkjCopyrightVo> copyrightTrendList(Date startTime, Date endTime, String projectName, String mobile) {
        PageHelper.clearPage(); // 清除PageHelper的状态

        // 查询订单
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByLists(startTime, endTime, projectName);

        // 创建一个 map 用于存储结果，key 为门店名称+投资方+日期
        Map<String, SlkjCopyrightVo> resultMap = new HashMap<>();

        for (SlkjOrder order : slkjOrders) {
            if (order.getBusinessStatus().equals(OrderBusinessStatus.COMPLETED.getCode())) {
                Project project = projectMapper.selectProjectByProjectId(order.getProjectId());
                SlkjCopyright copyright = slkjCopyrightMapper.selectSlkjCopyrightByCopyrightId(project.getCopyrightId());
                if (copyright.getMobile().equals(mobile)) {
                    // 获取订单日期
                    LocalDate orderDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                    // 构造 key
                    String key = project.getName() + "-" + copyright.getCompanyName() + "-" + orderDate;

                    // 查询分账快照
                    List<SlkjOrderSplitSnapshot> snapshots = slkjOrderSplitSnapshotMapper.selectByOrderId(order.getOrderId());

                    // 累加或创建记录
                    SlkjCopyrightVo vo = resultMap.get(key);
                    if (vo == null) {
                        vo = new SlkjCopyrightVo();
                        vo.setCreateTime(order.getCreateTime()); // 保留原始时间戳，用于排序
                        vo.setProjectName(project.getName());
                        vo.setCopyrightName(copyright.getCompanyName());
                        vo.setAmount("0");
                        resultMap.put(key, vo);
                    }

                    for (SlkjOrderSplitSnapshot snapshot : snapshots) {
                        if (snapshot.getRelatedType().equals(RelatedType.PROJECT.getCode())) {
                            long total = MoneyUtils.yuan2Hao(vo.getAmount()) + snapshot.getProfitShareAmount();
                            vo.setAmount(MoneyUtils.hao2Yuan(total));
                        }
                    }
                }
            }
        }

        // 将 map 的值转换为 list，并按时间降序排序
        List<SlkjCopyrightVo> copyrightVos = new ArrayList<>(resultMap.values());
        copyrightVos.sort(Comparator.comparing(SlkjCopyrightVo::getCreateTime).reversed());

        return copyrightVos;
    }

    @Override
    public List<SlkjCopyrightVo> exportCopyrightDetail(Date startTime, Date endTime, Long shopId, String projectName, boolean b) {
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderLists(startTime, endTime, shopId, projectName);
        if (CollectionUtils.isEmpty(slkjOrders)) {
            return Lists.newArrayList();
        }
        List<SlkjCopyrightVo> slkjCopyrightVos = new ArrayList<>();
        for (SlkjOrder order : slkjOrders) {
            if (order.getBusinessStatus().equals(OrderBusinessStatus.COMPLETED.getCode())) {
                // 获取项目信息
                Project project = projectMapper.selectProjectByProjectId(order.getProjectId());
                String projectNames = project.getName();

                // 获取版权方信息
                SlkjCopyright copyright = slkjCopyrightMapper.selectSlkjCopyrightByCopyrightId(project.getCopyrightId());

                // 将创建时间转换为只包含日期的部分
                LocalDate orderDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                // 查找是否有已存在的记录
                boolean found = false;
                for (SlkjCopyrightVo existingVo : slkjCopyrightVos) {
                    LocalDate existingDate = existingVo.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                    if (existingDate.equals(orderDate) && existingVo.getProjectName().equals(order.getProjectName())) {
                        // 如果日期和项目名称相同，累加金额
                        List<SlkjOrderSplitSnapshot> snapshots = slkjOrderSplitSnapshotMapper.selectByOrderId(order.getOrderId());
                        for (SlkjOrderSplitSnapshot snapshot : snapshots) {
                            if (snapshot.getRelatedType().equals(RelatedType.PROJECT.getCode())) {
                                long total = MoneyUtils.yuan2Hao(existingVo.getAmount()) + snapshot.getProfitShareAmount();
                                existingVo.setAmount(MoneyUtils.hao2Yuan(total));
                            }
                        }
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    // 如果没有找到相同的日期和项目名称，则创建新记录并添加到列表中
                    SlkjCopyrightVo slkjCopyrightVo = new SlkjCopyrightVo();
                    slkjCopyrightVo.setCopyrightName(copyright.getCompanyName());
                    slkjCopyrightVo.setCreateTime(order.getCreateTime());
                    slkjCopyrightVo.setShopName(order.getShopName());
                    slkjCopyrightVo.setProjectName(projectNames);

                    List<SlkjOrderSplitSnapshot> snapshots = slkjOrderSplitSnapshotMapper.selectByOrderId(order.getOrderId());
                    for (SlkjOrderSplitSnapshot snapshot : snapshots) {
                        if (snapshot.getRelatedType().equals(RelatedType.PROJECT.getCode())) {
                            slkjCopyrightVo.setAmount(MoneyUtils.hao2Yuan(snapshot.getProfitShareAmount()));
                        }
                    }
                    slkjCopyrightVos.add(slkjCopyrightVo);
                }
            }
        }
        // 在返回之前进行倒序排序
        slkjCopyrightVos.sort(Comparator.comparing(SlkjCopyrightVo::getCreateTime).reversed());
        return slkjCopyrightVos;
    }

    @Override
    public List<SlkjCopyrightVo> exportCopyrightSummary(Date startTime, Date endTime, Long shopId) {
        // 查询订单
        List<SlkjOrder> slkjOrders = slkjOrderMapper.selectSlkjOrderByList(startTime, endTime, shopId);
        if (CollectionUtils.isEmpty(slkjOrders)) {
            return new ArrayList<>();
        }

        // 创建一个 map 用于存储结果，key 为门店名称+投资方
        Map<String, SlkjCopyrightVo> resultMap = new HashMap<>();

        for (SlkjOrder order : slkjOrders) {
            if (order.getBusinessStatus().equals(OrderBusinessStatus.COMPLETED.getCode())) {
                Project project = projectMapper.selectProjectByProjectId(order.getProjectId());
                SlkjCopyright copyright = slkjCopyrightMapper.selectSlkjCopyrightByCopyrightId(project.getCopyrightId());

                // 获取订单日期
                LocalDate orderDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                // 构造 key
                String key = order.getShopName() + "-" + copyright.getCompanyName();

                // 查询分账快照
                List<SlkjOrderSplitSnapshot> snapshots = slkjOrderSplitSnapshotMapper.selectByOrderId(order.getOrderId());

                // 累加或创建记录
                SlkjCopyrightVo vo = resultMap.get(key);
                if (vo == null) {
                    vo = new SlkjCopyrightVo();
                    vo.setCreateTime(order.getCreateTime()); // 保留原始时间戳，用于排序
                    vo.setShopName(order.getShopName());
                    vo.setCopyrightName(copyright.getCompanyName());
                    vo.setAmount("0");
                    vo.setRatio(null); // 初始化比例
                    resultMap.put(key, vo);
                }

                for (SlkjOrderSplitSnapshot snapshot : snapshots) {
                    if (snapshot.getRelatedType().equals(RelatedType.PROJECT.getCode())) {
                        long total = MoneyUtils.yuan2Hao(vo.getAmount()) + snapshot.getProfitShareAmount();
                        vo.setAmount(MoneyUtils.hao2Yuan(total));
                        vo.setRatio(snapshot.getSplitRatio()); // 更新比例
                    }
                }
            }
        }

        // 将 map 的值转换为 list，并按时间降序排序
        List<SlkjCopyrightVo> copyrightVos = new ArrayList<>(resultMap.values());
        copyrightVos.sort(Comparator.comparing(SlkjCopyrightVo::getCreateTime).reversed());
        return copyrightVos;
    }

}